package com.amigo.online.provider.manager.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.amigo.online.common.base.service.BaseService;
import com.amigo.online.provider.manager.mapper.ApplyConfirmationMapper;
import com.amigo.online.provider.manager.model.entity.ApplyConfirmationTbl;
import com.amigo.online.provider.manager.model.entity.ApplyTbl;
import com.amigo.online.provider.manager.service.ApplyConfirmationService;
import com.amigo.online.provider.manager.mapper.ApplyTblMapper;

@Service
public class ApplyConfirmationServiceImpl extends BaseService<ApplyConfirmationTbl>
        implements ApplyConfirmationService {
    @Resource
    private ApplyConfirmationMapper applyConfirmationMapper;

    @Resource
    private ApplyTblMapper applyTblMapper;

    @Override
    @Transactional
    public int update(ApplyConfirmationTbl applyConfirmationTbl) {
        // 根据apply_id获取信息
        List<ApplyConfirmationTbl> applyNumber = applyConfirmationMapper.findApplyNumber(applyConfirmationTbl);
        List<ApplyConfirmationTbl> updateList = new ArrayList<>();
        for (ApplyConfirmationTbl tempObj : applyNumber) {
            // 地区剩余播放量
            int as = tempObj.getAreaSurplus();
            // 套餐所需每天播放量
            int code = tempObj.getCode();
            // 投放地区id
            int areaid = tempObj.getAreaId();
            // 地区的视频播放总量
            // int advn = tempObj.getAdvnumber();
            // 冻结量
            int fzb = tempObj.getFreezenumber();
            Long showdate = tempObj.getShowDate();
            // 播放占比
            // double weight = new BigDecimal((float) code / advn).setScale(4,
            // BigDecimal.ROUND_HALF_UP).doubleValue();
            if (as < code)
                return -1;
            else
                // 添加冻结量
                tempObj.setFreezenumber(code + fzb);
            // 地址id
            tempObj.setAreaId(areaid);
            // 添加开始时间
            tempObj.setShowDate(showdate);
            // 占比
            // tempObj.setWeight(weight);
            tempObj.setStatus(1);
            tempObj.setApplynumber(code);
            tempObj.setRestnumber(code);
            updateList.add(tempObj);

        }
        ApplyTbl at = new ApplyTbl();

        at.setId(applyConfirmationTbl.getId());
        at.setCheckstatus(applyConfirmationTbl.getCheckstatus());
        // 修改冻结量
        int ac = applyConfirmationMapper.updateApplyNumber(updateList);
        // 添加到库存表
        int as = applyConfirmationMapper.saveAdvStock(updateList);
        // 修改审核状态
        int aut = applyTblMapper.updateCheckstatus(at);
        if (ac <= 0 && as <= 0 && aut <= 0) {
            return -1;
        } else {
            return 1;
        }

    }

}
